import axios from '@/utils/request'
let store = 0
const ORDER_STATUS = {
  '-2': '支付失败',
  '-1': '已取消',
  1: '已提交',
  2: '已支付',
  3: '已发货',
  4: '已结算',
  5: '已完成'
}
const STATUS_COLOR = {
  '-2': 'danger',
  '-1': 'info',
  1: 'primary',
  2: 'warning',
  3: 'warning',
  4: 'success',
  5: 'success'
}

export default {
  StoreOrderItem: {
    entity: {
      name: 'OrderItem', prefix: () => {
        store = localStorage.getItem('storeId')
        return `store/${store}`
      }
    },
    form: {
      fields: [
        'id'
      ]
    },
    list: {
      export: {
        query: {
          '@display': `{
            'id' : 'entity.getId()',
            'outTradeNo': 'entity.getOrder().getInvoice().getOutTradeNo()',
            'createdTime' : 'entity.getCreatedTime().format("Y-m-d H:i:s")',
            'staff' : 'entity.getOrder().getStaff().__toString()',
            'squad' : 'entity.getOrder().getSquad().__toString()',
            'leader' : 'entity.getOrder().getLeader().__toString()',
            'broker' : 'entity.getOrder().getBroker().__toString()',
            'item' : 'entity.__toString()',
            'status' : '{ "-2": "支付失败", "-1": "已取消", 1: "已提交", 2: "已支付", 3: "已发货", 4: "已结算", 5: "已完成" }[entity.getOrder().getStatus()]',
            'price' : 'entity.getPrice()',
            'totalPrice' : 'entity.getOrder().getTotalPrice()',
            'laterPay': 'entity.getOrder().getLaterPay() ? "待结账" : "已结账"',
            'comment': 'entity.getOrder().getComment()'
          }`,
          limit: 10000000
        },
        label: {
          'id': 'id',
          'outTradeNo': '支付单号',
          'createdTime': '创建时间',
          'staff': '业务',
          'squad': '小队',
          'leader': '队长',
          'broker': '经纪人',
          'item': '项目',
          'status': '状态',
          'price': '金额',
          'totalPrice': '订单总价',
          'laterPay': '支付状态',
          'comment': '订单备注'
        }
      },
      disabled_actions: ['new', 'delete', 'edit', 'lines'],
      query: {
        '@order': 'entity.id|DESC',
        '@expands': "['entity.order.invoice','entity.shippings']"
      },
      list_filter: {
        'order.status': Object.assign({ __label: '订单状态' }, ORDER_STATUS),
        beforeCreatedTime: {
          expression: 'entity.getCreatedTime() >= datetime.get(":value 08:00:00")',
          label: '下单开始时间',
          type: 'date'
        },
        afterCreatedTime: {
          expression: 'entity.getCreatedTime() < datetime.get(":value 07:59:59")',
          label: '下单结束时间',
          type: 'date'
        },
        'order.squad.id': () => {
          return axios
            .get(`/store/${store}/squads`)
            .then(res =>
              Object.assign({ __label: '小队' },
                ...res.data.map(v => { return { [v.id]: v.name } })))
        },
        'staff': {
          expression: 'entity.getOrder().getStaff().getId() == ":value"',
          label: '业务员/工号',
          type: 'remote-select',
          data: [],
          remoteMethod: (query, context) => {
            axios
              .get(`/store/${store}/staffs`, { params: { '@filter': `entity.getName() matches "${query}" || entity.getId() matches "${query}"` } })
              .then(res => {
                context.data = res.data.map(v => { return { value: v.id, label: v.id + v.name } })
              })
          }
        },
        // 'specification.id': () => {
        //   return axios
        //     .get(`/store/${store}/specifications`, {
        //       params: {
        //         '@order': `entity.listOrder|ASC`
        //       }})
        //     .then(res =>
        //       Object.assign({ __label: '产品' },
        //         ...res.data.map(v => { return { [v.id]: v.name } })))
        // }
      },
      list_display: [
        'id',
        'createdTime',
        { property: 'order.__metadata.name', label: '客户' },
        { property: 'order.__metadata.phone', label: '电话' },
        { property: 'order.__metadata.address', label: '地址' },
        {
          property: 'specificationTitle',
          label: '产品'
        },
        {
          property: 'quantity',
          label: '数量'
        },
        {
          property: 'shippings',
          label: '已发货',
          component: {
            props: ['data'],
            data() {
              return {
                shippingedQuantity: 0
              }
            },
            created() {
              if (this.data && this.data.length > 0) {
                let quantity = 0
                for (let i of this.data) {
                  quantity += parseInt(i.__metadata.quantity)
                }
                this.shippingedQuantity = quantity
              }
            },
            render(h) {
              return <span>{this.shippingedQuantity}</span>
            }
          }
        },
        {
          property: 'order.__metadata.status',
          label: '订单状态',
          component: {
            props: ['data'],
            data() {
              return {
                status: ORDER_STATUS,
                color: STATUS_COLOR
              }
            },
            render(h) {
              return <el-tag type={this.color[this.data]} effect='plain'>{this.status[this.data]}</el-tag>
            }
          }
        },
        { property: 'price', label: '金额' },
        { property: 'order.__metadata.totalPrice', label: '订单总价' },
        { property: 'order.__metadata.staff.__toString', label: '业务' },
        { property: 'order.__metadata.squad.__toString', label: '所属小队' },
        { property: 'order.__metadata.leader.__toString', label: '队长' },
        { property: 'order.__metadata.broker.__toString', label: '经纪人' },
        { property: 'order.__metadata.comment', label: '订单备注' }
      ]
    }
  }
}
